<template>
  <div
    class="c-editor-collaboration-bar__dropdown-content"
    :style="{ '--right': props.right }"
  >
    <div class="dropdown-content__header">
      <a-flex justify="space-between" align="center">
        <div class="dropdown-content__title">
          {{
            props.type === 1
              ? `协作列表（${collaborativeData.onLineCount}/${collaborativeData.totalCount}人）`
              : `邀请加入「${collaborativeData.boardName}」白板协作`
          }}
        </div>
        <CloseOutlined
          class="dropdown-content__close-icon"
          @click="closeModal"
        />
      </a-flex>
    </div>

    <!--  协作列表  -->
    <div v-if="props.type === 1">
      <a-divider style="margin: 0" />
      <a-row justify="center" align="middle">
        <a-col
          :span="24"
          class="invite-list-item"
          v-for="item in userList"
          :key="item.memberId"
        >
          <a-row justify="space-around" align="middle" style="height: 100%">
            <a-col :span="18">
              <a-avatar :src="item.avatarUrl" style="margin: 0 10px"></a-avatar>
              <span style="font-weight: 400">
                {{ item.nickname }}
              </span>
            </a-col>
            <a-col :span="6">
              <a-dropdown
                placement="bottomRight"
                :trigger="['click']"
                :disabled="item.isMe || item.role <= collaborativeData.myRole"
              >
                <span class="select">
                  {{
                    item.role === boardRole.Owner
                      ? '拥有者'
                      : item.role === boardRole.Editor
                        ? '编辑者'
                        : '浏览者'
                  }}
                  <DownOutlined
                    v-show="
                      !(item.isMe || item.role <= collaborativeData.myRole)
                    "
                  />
                </span>
                <template #overlay>
                  <a-menu>
                    <div v-show="item.role > boardRole.Editor">
                      <a-menu-item
                        :key="1"
                        @click="changeMemberRole(item.memberId, '1')"
                      >
                        编辑者
                      </a-menu-item>
                    </div>
                    <div v-show="item.role < boardRole.Viewer">
                      <a-menu-item
                        :key="2"
                        @click="changeMemberRole(item.memberId, '2')"
                      >
                        浏览者
                      </a-menu-item>
                    </div>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-col>
          </a-row>
        </a-col>
      </a-row>
    </div>
    <!--  协作分享  -->
    <div v-if="props.type === 2">
      <a-divider style="margin: 0 0 10px 0" />
      <a-row
        justify="center"
        align="middle"
        :gutter="[3, 10]"
        style="margin: 20px 10px"
      >
        <a-col :span="21">
          <a-input
            value="https://colaboard.online/board-invite/********"
            disabled
          />
        </a-col>
        <a-col :span="2">
          <a-tooltip title="重置链接" placement="bottom" :mouse-enter-delay="1">
            <a-button @click="() => (inviteData.resetModalVisible = true)">
              <template #icon><ReloadOutlined /></template>
            </a-button>
          </a-tooltip>
        </a-col>
        <a-col :span="6" style="color: #696969">白板协作权限</a-col>
        <a-col :span="17">
          <a-select
            v-model:value="inviteData.auth"
            style="width: 100%"
            @change="getInviteUrl"
          >
            <a-select-option value="1">编辑者</a-select-option>
            <a-select-option value="2">浏览者</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="23">
          <a-button type="primary" block class="copy_board_invite_btn">
            复制链接
          </a-button>
        </a-col>
      </a-row>
    </div>
    <a-modal
      v-model:open="inviteData.resetModalVisible"
      title="重置链接"
      :body-style="{
        padding: '24px 0',
      }"
      :mask-style="{ backgroundColor: 'rgba(255,255,255,0.7)' }"
      :maskClosable="false"
      centered
    >
      {{
        `重置链接后，协作伙伴将无法再次通过旧链接加入团队。确认重置链接吗？（仅重置${
          inviteData.auth === '1' ? '编辑权限' : '查看权限'
        }的链接）`
      }}
      <template #footer>
        <a-button
          key="back"
          @click="() => (inviteData.resetModalVisible = false)"
        >
          取消
        </a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="inviteData.resetLoading"
          @click="resetInviteUrl"
        >
          确定
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import {
  CloseOutlined,
  DownOutlined,
  ReloadOutlined,
} from '@ant-design/icons-vue';
import {
  inject,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
  watchEffect,
} from 'vue';
import { IEditor } from '@/types/global';
import { boardRole, BoardSyncEvent } from '@/utils/Const.ts';
import { useBoardStore } from '@/store';
import { message } from 'ant-design-vue';
import Clipboard from 'clipboard';

// 白板编辑器对象，操作画布
const canvasEditor: unknown | IEditor = inject('canvasEditor');
const props = defineProps({
  right: {
    type: String,
    default: '0',
  },
  type: {
    type: Number,
    required: true,
  },
  showInviteModal: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(['closeModal']);
const boardStore = useBoardStore();

// 协作邀请 数据
let clipboard: any;
const inviteData = reactive({
  inviteLink: '',
  auth: '1',
  resetModalVisible: false,
  resetLoading: false,
});
// 协作数据
const collaborativeData = reactive({
  onLineCount: 0,
  totalCount: 0,
  myRole: -1,
  boardName: '',
});
const userList = ref<Array<any>>([]);

onMounted(() => {
  // 更新协作列表数据
  canvasEditor.on(BoardSyncEvent.type2, (data: any) => {
    userList.value = data.memberVOList;
    collaborativeData.myRole = data.myRole;
    collaborativeData.totalCount = data.memberVOList.length;
    const onlineList = data.memberVOList.filter((item: any) => item.isOnline);
    collaborativeData.onLineCount = onlineList.length;
  });
  // 获取白板数据
  canvasEditor.on(BoardSyncEvent.type0, (data: any) => {
    collaborativeData.boardName = data.name;
  });
  if (props.type === 2) {
    // 复制链接
    clipboard = new Clipboard('.copy_board_invite_btn', {
      text: function () {
        return `点击一起协作白板「${collaborativeData.boardName}」并加入我的团队\n${inviteData.inviteLink}`;
      },
    });
    clipboard.on('success', () => {
      message.success('复制链接成功');
    });
    clipboard.on('error', () => {
      message.error('复制链接失败');
    });
  }
});
// 仅打开协作邀请面板时发送获取邀请链接请求
const watch = watchEffect(async () => {
  if (props.showInviteModal) {
    await getInviteUrl();
  }
});
onBeforeUnmount(() => {
  watch();
});
// 修改白板成员角色
async function changeMemberRole(memberId: string, roleCode: string) {
  const res = await boardStore.changeBoardMemberRole(memberId, roleCode);
  if (res?.code === 0) {
    message.success('修改白板成员权限成功');
  }
  console.log('修改白板成员角色', res);
}
// 重置白板邀请链接
async function resetInviteUrl() {
  inviteData.resetLoading = true;
  const res = await boardStore.resetBoardInviteUrl(inviteData.auth);
  if (res?.code === 0) {
    const response = await boardStore.getBoardInviteUrl(inviteData.auth);
    if (response?.code === 0) {
      inviteData.inviteLink = response.data;
      message.success('邀请链接重置成功');
    }
  }
  inviteData.resetLoading = false;
  inviteData.resetModalVisible = false;
}
// 获取白板邀请链接
async function getInviteUrl() {
  const res = await boardStore.getBoardInviteUrl(inviteData.auth);
  if (res?.code === 0) {
    inviteData.inviteLink = res.data;
  }
}

onBeforeUnmount(() => {
  // 销毁内存
  clipboard?.destroy();
});
function closeModal() {
  emit('closeModal');
}
</script>

<style scoped lang="scss">
.c-editor-collaboration-bar__dropdown-content {
  position: absolute;
  top: 45px;
  right: var(--right);
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 -3px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 999;
  width: 24rem;
  .dropdown-content__header {
    padding: 15px;
    .dropdown-content__title {
      font-size: 1rem;
      font-weight: bold;
    }
    .dropdown-content__close-icon {
      cursor: pointer;
      font-size: 14px;
      color: rgb(88, 97, 119);
      padding: 5px;
      user-select: none;
      &:hover {
        background: rgba(185, 185, 185, 0.2);
      }
    }
  }
  .invite-list-item {
    height: 4rem;
    padding: 10px;
    &:hover {
      background: rgba(185, 185, 185, 0.2);
    }
  }
}
.select {
  color: rgba(2, 2, 2, 0.65);
  cursor: pointer;
}
</style>
